
from rest_framework import serializers, pagination

from .models import Article, Category


class ArticleSerializer(serializers.HyperlinkedModelSerializer):
    category = serializers.SlugRelatedField(
        read_only=True,
        slug_field='name',
    )

    tag = serializers.SlugRelatedField(
        read_only=True,
        slug_field='name',
    )

    create_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S')

    class Meta:
        model = Article
        fields = ['id', 'title', 'category', 'tag', 'desc', 'create_time']
        extra_kwargs = {
            'url': {'view_name': 'api-article-detail'}
        }


class ArticleDetailSerializer(ArticleSerializer):
    class Meta:
        model = Article
        fields = ['id', 'title', 'category', 'tag', 'desc', 'create_time']


class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Category
        fields = ['id', 'name', 'create_time',]


class CategoryDetailSerializer(CategorySerializer):
    articles = serializers.SerializerMethodField('paginated_articles')

    def paginated_articles(self, obj):
        articles = obj.article_set.filter(status=Article.STATUS_NORMAL)
        paginator = pagination.PageNumberPagination()
        page = paginator.paginate_queryset(articles, self.context['request'])
        serializer = ArticleSerializer(page, many=True, context={'request': self.context['request']})

        return {
            'results': serializer.data,
            'previous': paginator.get_previous_link(),
            'next': paginator.get_next_link(),
        }

    class Meta:
        model = Category
        fields = ['id', 'name', 'create_time', 'articles']
